package com.cipe.cmrs.controllers;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.cipe.cmrs.bean.AuditsBean;
import com.cipe.cmrs.converter.DateEditor;
import com.cipe.cmrs.service.AuditsService;
import com.cipe.cmrs.util.CollectionUtil;
import com.cipe.cmrs.util.Constants;
import com.cipe.cmrs.util.UserUtil;
import com.cipe.cmrs.validator.AuditsValidator;

/**
 * Add/Edit form for Audits. This is used for Partner Monitoring View
 * 
 * @author Allan Ramirez (ramirezag@gmail.com)
 * 
 */
@Controller
@RequestMapping("/secure/auditsForm.do")
public class AuditsFormController extends BaseController {
	public static final String REDIRECT_TO_AUDIT_LIST_PAGE = "redirect:auditsForm.do?cipeprojectId=";
    protected static final String COMMAND_NAME = "audits";

    /**
	 * 
	 */
    private static final long serialVersionUID = -1263199606542203874L;
    private static final String FORM_VIEW = "project/auditsForm";

    @Autowired
    protected AuditsService service;
    @Autowired
    private AuditsValidator validator;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
		super.initBinder(binder);
    }

    @ModelAttribute(COMMAND_NAME)
    public AuditsBean getCommand(@RequestParam(value = "cipeprojectId") Integer cipeprojectId) {
        return service.getAuditByProjectId(cipeprojectId);
    }

    @RequestMapping(method = RequestMethod.GET)
    protected ModelAndView getFormView(@ModelAttribute(COMMAND_NAME) AuditsBean bean, HttpServletRequest request) {
        return new ModelAndView(FORM_VIEW).addAllObjects(getReferenceData(bean, request));
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) AuditsBean bean, BindingResult result, HttpServletRequest request,
        SessionStatus status) {
        ModelAndView mav = null;
        CollectionUtil.INSTANCE.trimList(bean.getImpBeans(), bean.getImpBeansSize());
        validator.validate(result, bean);
        if (result.hasErrors()) {
            mav = getFormView(bean, request).addObject(COMMAND_NAME, bean);
            mav.addAllObjects(result.getModel());
            saveError(request, result.getGlobalErrors());
        } else {
            try {
                if (bean.getUser() == null) {
                    bean.setUser(UserUtil.INSTANCE.getCurrentUser());
                }
                service.save(bean);
                saveMessage(request, getText("partnermonitoring.message.sucess"));
                status.setComplete();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(getText("error.transaction"), e);
                saveError(request, getText("error.transaction"));
            }

            mav = getFormView(bean, request).addObject(COMMAND_NAME, bean);
        }
        return mav;
    }

    protected Map<String, Object> getReferenceData(AuditsBean bean, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        populateAuditsBeanDueDates(bean, map);
        return map;
    }

	private void populateAuditsBeanDueDates(AuditsBean bean, Map<String, Object> map) {
		if (bean.getProject() != null && bean.getProject().getStartDate() != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(bean.getProject().getStartDate());
			cal.add(Calendar.MONTH, 3);
//			Interim Selection Memo Due Date
			map.put("iaselectionmemodue", cal.getTime());
		}
		if (bean.getProject() != null && bean.getProject().getStartDate() != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(bean.getProject().getStartDate());
			cal.add(Calendar.MONTH, 8);
			map.put("iadue", cal.getTime());
		}

		if (bean.getProject() != null && bean.getProject().getEndDate() != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(bean.getProject().getEndDate());
			cal.add(Calendar.DATE, -30);
			map.put("faselectionmemodue", cal.getTime());
		}
		if (bean.getProject() != null && bean.getProject().getEndDate() != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(bean.getProject().getEndDate());
			cal.add(Calendar.MONTH, 2);
			map.put("fadue", cal.getTime());
		}
	}

}
